//
//  WorkFinishController.swift
//  vmes
//
//  Created by 志鹏 翟 on 2021/12/2.
//

import UIKit
import Alamofire

class WorkFinishController: BaseController , UITextFieldDelegate {
    
    let top=UIView()
    let planNum=UILabel()
    let alreadyNum=UILabel()
    let waitNum=UILabel()
    let contentView=UIView()
    
    //创建textField
    let textField_zidong = UITextField()
    let textField_zidongbuliang = UITextField()
    let textField_baogong = UITextField()
    let textField_baogongbuliang = UITextField()
    
    var orderInfo:OrderItem?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        NotificationCenter.default.addObserver(self, selector: #selector(self.kbFrameChanged(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        title="当班完工"
        view.backgroundColor = .white
        let scrollview=UIScrollView()
        
        view.addSubview(scrollview)
        scrollview.addSubview(contentView)
        scrollview.snp.makeConstraints { make in
            make.edges.equalTo(view)
        }
        contentView.snp.makeConstraints { make in
            make.edges.equalTo(scrollview)
            make.width.equalTo(view)
        }
        
        top.backgroundColor=UIColor.colorWithHex(hexStr: "#E3E5E7")
        top.layer.cornerRadius=10
        contentView.addSubview(top)
        top.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaInsets.top+20)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(130)
        }
        let orderNoLb=UILabel()
        orderNoLb.text="orderNo"
        let desc1Lb=UILabel()
        let desc2Lb=UILabel()
        let statusLb=UILabel()
        statusLb.text="生产中"
        let materialTxt=UILabel()
        let materialColor=UILabel()
        materialTxt.font = .systemFont(ofSize: 14)
        materialColor.font = .systemFont(ofSize: 14)
        
        materialTxt.text="物料材质：" + (orderInfo?.materialText ?? "空")
        materialColor.text="物料颜色：" + (orderInfo?.materialColo ?? "无")
        
        [orderNoLb,statusLb,desc1Lb,desc2Lb,materialTxt,materialColor].forEach {
            top.addSubview($0)
        }
        orderNoLb.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(20)
        }
        materialTxt.snp.makeConstraints { make in
            make.left.equalTo(orderNoLb.snp.left)
            make.top.equalTo(orderNoLb.snp.bottom).offset(10)
        }
        materialColor.snp.makeConstraints { make in
            make.left.equalTo(materialTxt.snp.right).offset(10)
            make.top.equalTo(materialTxt.snp.top)
        }
        desc1Lb.snp.makeConstraints { make in
            make.left.equalTo(orderNoLb.snp.left)
            make.top.equalTo(materialTxt.snp.bottom).offset(10)
        }
       
        desc2Lb.snp.makeConstraints { make in
            make.left.equalTo(orderNoLb.snp.left)
            make.top.equalTo(desc1Lb.snp.bottom)
        }
        statusLb.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(orderNoLb.snp.top)
        }
        orderNoLb.text=orderInfo?.workorderCode
        desc1Lb.text=orderInfo?.productCode ?? "暂无产品内容"
        desc2Lb.text=orderInfo?.productName ?? "暂无产品内容"
        if("0"==orderInfo?.statusFlag!){
            statusLb.text="待生产"
        }else if("1"==orderInfo?.statusFlag!){
            statusLb.text="当班开工"
        }else if("2"==orderInfo?.statusFlag!){
            statusLb.text="当班完工"
        }else if("3"==orderInfo?.statusFlag!){
            statusLb.text="已完成"
        }
        initNumLabel()
        initInputArea()
        getAcqNum()
    }
    
    func initNumLabel(){
        let planNumLb=UILabel()
        let allNumLb=UILabel()
        let waitNumLb=UILabel()
        planNumLb.text="总排产量"
        allNumLb.text="已报工量"
        waitNumLb.text="当班计划量"
        [planNumLb,allNumLb,waitNumLb].forEach({
            contentView.addSubview($0)
            $0.textAlignment = .center
            $0.textColor=UIColor.colorWithHex(hexStr: "#333333")
            $0.font = UIFont.systemFont(ofSize: 15)
        })
        planNumLb.snp.makeConstraints { make in
            make.width.equalTo(width/3)
            make.top.equalTo(top.snp.bottom).offset(20)
        }
        allNumLb.snp.makeConstraints { make in
            make.width.equalTo(width/3)
            make.top.equalTo(top.snp.bottom).offset(20)
            make.left.equalTo(planNumLb.snp.right)
        }
        waitNumLb.snp.makeConstraints { make in
            make.width.equalTo(width/3)
            make.top.equalTo(top.snp.bottom).offset(20)
            make.left.equalTo(allNumLb.snp.right)
        }
        [planNum,alreadyNum,waitNum].forEach({
            contentView.addSubview($0)
            $0.textAlignment = .center
            $0.text="500"
            $0.textColor=UIColor.colorWithHex(hexStr: "#0FA386")
            $0.font = UIFont.systemFont(ofSize: 20)
        })
        planNum.snp.makeConstraints { make in
            make.centerX.equalTo(planNumLb.snp.centerX)
            make.top.equalTo(planNumLb.snp.bottom).offset(5)
        }
        alreadyNum.snp.makeConstraints { make in
            make.centerX.equalTo(allNumLb.snp.centerX)
            make.top.equalTo(planNumLb.snp.bottom).offset(5)
        }
        waitNum.snp.makeConstraints { make in
            make.centerX.equalTo(waitNumLb.snp.centerX)
            make.top.equalTo(planNumLb.snp.bottom).offset(5)
        }
        planNum.text=String(orderInfo?.scheduleNumber ?? 0)
        alreadyNum.text=String(orderInfo?.workreportOutput ?? 0)
        waitNum.text=String(orderInfo?.shiftPlanOutput ?? 0)
    }
    
    func initInputArea(){
        let area=UIView()
        area.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        contentView.addSubview(area)
        area.snp.makeConstraints { make in
            make.top.equalTo(planNum.snp.bottom).offset(40)
            make.height.equalTo(400)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(contentView)
        }
        let inner=UIView()
        inner.layer.cornerRadius=10
        inner.backgroundColor = .white
        area.addSubview(inner)
        inner.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(30)
            make.bottom.equalToSuperview().offset(-40)
        }
        
        
        [textField_zidong,textField_zidongbuliang,textField_baogong,textField_baogongbuliang].forEach({
            inner.addSubview($0)
            $0.textAlignment = .right
            $0.text="0"
            $0.keyboardType = .decimalPad
            $0.textColor=UIColor.colorWithHex(hexStr: "#0FA386")
            $0.font = UIFont.systemFont(ofSize: 20)
            //            $0.isEnabled=false
            $0.leftViewMode = .always
            $0.delegate = self
            $0.returnKeyType = .done
        })
        textField_baogong.delegate=self
        textField_baogong.text=""
        
        let label=UILabel()
        label.text="自动产量"
        textField_zidong.leftView = label
        textField_zidong.isEnabled=false
        textField_zidong.textColor = .gray
        
        let label2=UILabel()
        label2.text="自动不良品数"
        textField_zidongbuliang.leftView = label2
        textField_zidongbuliang.textColor = .gray
        textField_zidongbuliang.isEnabled=false
        
        let label3=UILabel()
        label3.text="报工产量"
        textField_baogong.leftView = label3
        
        let label4=UILabel()
        label4.text="报工不良品数"
        textField_baogongbuliang.leftView = label4
        
        textField_zidong.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
            make.top.equalToSuperview().offset(20)
        }
        let line=UIView()
        line.backgroundColor = UIColor.colorWithHex(hexStr: "#6F6F6F")
        inner.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
            make.top.equalTo(textField_zidong.snp.bottom)
        }
        textField_zidongbuliang.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
            make.top.equalTo(textField_zidong.snp.bottom).offset(10)
        }
        let line2=UIView()
        line2.backgroundColor = UIColor.colorWithHex(hexStr: "#6F6F6F")
        inner.addSubview(line2)
        line2.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
            make.top.equalTo(textField_zidongbuliang.snp.bottom)
        }
        textField_baogong.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
            make.top.equalTo(textField_zidongbuliang.snp.bottom).offset(10)
        }
        let line3=UIView()
        line3.backgroundColor = UIColor.colorWithHex(hexStr: "#6F6F6F")
        inner.addSubview(line3)
        line3.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
            make.top.equalTo(textField_baogong.snp.bottom)
        }
        textField_baogongbuliang.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
            make.top.equalTo(textField_baogong.snp.bottom).offset(10)
        }
        let line4=UIView()
        line4.backgroundColor = UIColor.colorWithHex(hexStr: "#6F6F6F")
        inner.addSubview(line4)
        line4.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
            make.top.equalTo(textField_baogongbuliang.snp.bottom)
        }
        let btn=UIButton()
        btn.layer.cornerRadius=5
        inner.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalTo(line4).offset(30)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(55)
        }
        btn.setTitle("提交完工信息", for: .normal)
        btn.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        btn.setTitleColor(UIColor.colorWithHex(hexStr: "#ffffff"), for: .normal)
        btn.addTarget(self, action: #selector(showConfrimAlert), for: .touchUpInside)
    }
    
    @objc func showConfrimAlert(){
        if textField_baogong.text == nil {
            self.view.makeToast("报工数量不能为空")
            return
        }
        if Float(textField_baogong.text!) == nil || Float(textField_baogong.text!) == 0 {
            self.view.makeToast("报工产量错误")
            return
        }
        if Float(textField_baogongbuliang.text!) == nil {
            self.view.makeToast("报工不良错误")
            return
        }
        let alertView = UIAlertController.init(title: "提示", message: "确认完工么", preferredStyle: .alert)
        let alert = UIAlertAction.init(title: "确定", style: .destructive) { (UIAlertAction) in
            self.finishWork()
        }
        let cancleAlert = UIAlertAction.init(title: "取消", style: .cancel) { (UIAlertAction) in
            print("点击取消按钮")
        }
        alertView.addAction(cancleAlert)
        alertView.addAction(alert);
        self.present(alertView, animated: true, completion: nil)
    }
    
    @objc func finishWork(){
        spinner.startAnimating()
        let parameters: Dictionary = [
            "compId" : K.userInfo?.company?.companyId!,
            "finishOperator" : K.userInfo?.userId!,
            "workorderCode" : orderInfo?.workorderCode!,
            "workshopId" : K.currentWorkShop?.workshopId!,
            "scheduleId":orderInfo?.id!,
            "workreportOutput" : textField_baogong.text,
            "workreportRejectNumber" : textField_baogongbuliang.text,
            "acqOutput" : textField_zidong.text,
            "acqRejectNumber" : textField_zidongbuliang.text,
            "shiftWorkId" : orderInfo?.tbBShiftWork?.id
        ]
        AF.request(NetInfo.finishWork, method:.put
                   , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!,
                   requestModifier: { $0.timeoutInterval = 10 }).responseJSON { (response) in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(LoginInfo.self, from: data)
                    if(response?.code==200){
                        self.view.makeToast("完工成功",duration:2)
                        self.perform(#selector(self.backItemPressed), with: nil, afterDelay: 2)
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        
        // 只允许输入数字和两位小数
        let expression =  "^[0-9]*((\\.|,)[0-9]{0,2})?$"
        // let expression = "^[0-9]*([0-9])?$" 只允许输入纯数字
        // let expression = "^[A-Za-z0-9]+$" //允许输入数字和字母
        let regex = try!  NSRegularExpression(pattern: expression, options: .allowCommentsAndWhitespace)
        let numberOfMatches =  regex.numberOfMatches(in: newString, options:.reportProgress,    range:NSMakeRange(0, newString.count))
        if  numberOfMatches == 0{
//            print("请输入数字")
            return false
        }
        
        if newString.count>10{
            return false
        }
        return true
    }
    
    func getAcqNum(){
        let parameters: Dictionary = [
            "scheduleId" : orderInfo?.id,
            "workOrderCode" : orderInfo?.workorderCode
        ]
        AF.request(NetInfo.acqResult, method:.get
                   , parameters:parameters,headers: K.headers!,
                   requestModifier: { $0.timeoutInterval = 10 }).responseJSON { (response) in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(AcqModel.self, from: data)
                    if(response?.code==200){
                        self.textField_zidong.text=String(response?.data?.acqOutPut ?? 0)
                        self.textField_zidongbuliang.text=String(response?.data?.acqRejectNumber ?? 0)
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
    
}
